﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Business;
public partial class admin_Mng_Faults : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            loadFaultsCondition();
        else
        {

            //    dt_result =(DataTable)  Session["dt"];
            //   GridView1.DataSource = dt_result;
            //  GridView1.DataBind();
        }
       
    }
    protected void loadFaultsCondition()
    {
        string query = "SELECT * FROM FaultsCondition WHERE faultType!=0";
        try
        {
            CreateConn objcon = new CreateConn();
            DataTable dt = objcon.SQLConnDataTable(query);
            if (dt.Rows.Count > 0)
            {
                dt.Columns.Add("Component");
                foreach (DataRow dr in dt.Rows)
                {
                    string fault_id = dr["fault_id"].ToString();
                    dr.BeginEdit();
                    try
                    {

                        dr["Component"] = this.IntToString(getFaultsComponent(Int32.Parse(fault_id)));//change the value
                    }
                    catch (Exception e)
                    {
                        Response.Write(e.ToString());
                    }
                }
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }
        catch(Exception e)
        {
            Response.Write(e.ToString());
        }
    }
    protected void PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        //指定新页面，重新绑定数据 
        GridView1.PageIndex = e.NewPageIndex;
        loadFaultsCondition();
        GridView1.DataBind();
    }
    protected void TaskGridView_RowEditing(object sender, GridViewEditEventArgs e)
    {
        //Set the edit index.
        GridView1.EditIndex = e.NewEditIndex;
        //Bind data to the GridView control.
        loadFaultsCondition();
        //GridView1.DataBind();
    }
    protected void TaskGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        //Reset the edit index.
        GridView1.EditIndex = -1;
        //Bind data to the GridView control.
        GridView1.DataBind();

        // BindData();
    }
    protected void TaskGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
       // GridViewRow row = GridView1.Rows[e.RowIndex];
        TableCell cell =  GridView1.Rows[e.RowIndex].Cells[3];
        string str = cell.Text;
        //String str = ((TextBox)row.Cells[1].Controls[0]).Text;
       // int fault_id = Int32.Parse(((TextBox)(row.Cells[3].Controls[0])).Text);
        int fault_id = Int32.Parse(str.Trim());
        String delete_query = "DELETE FROM FaultsCondition WHERE fault_id='"+fault_id+"'";
        try
        {
            CreateConn objcon = new CreateConn();
            objcon.SQLConnDataTable(delete_query);
            string delete_faultscomponentrelationship = "DELETE FROM Category_Fault WHERE fault_id='"+fault_id+"'";
            CreateConn objcon2 = new CreateConn();
            objcon2.SQLConnDataTable(delete_faultscomponentrelationship);
        }catch(Exception e2){
            Response.Write(e2.ToString());
        }
        loadFaultsCondition();
    }
    protected void TaskGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        //Retrieve the table from the session object.
        //DataTable dt = (DataTable)Session["dt"];
        //){
        //}
        //Update the values.
        GridViewRow row = GridView1.Rows[e.RowIndex];
        string faulttitle = ((TextBox)(row.Cells[1].Controls[1])).Text;
        string faultdes = ((TextBox)(row.Cells[2].Controls[1])).Text;
        DropDownList faultsDroplist = (DropDownList)row.Cells[0].FindControl("dropdownlist_component");
        int faultcomponentID = Int32.Parse(faultsDroplist.SelectedValue);
        int count = row.Cells.Count;
        //   Label lb = (Label) row.Cells[6].Controls[0];
        int fault_id = Int32.Parse(((TextBox)(row.Cells[3].Controls[0])).Text);
        this.UpdateFaultsComponentRealtionship(fault_id,faultcomponentID);
        string query = "Update FaultsCondition set faultName='" + faulttitle + "',faultDes='"
            + faultdes + "' WHERE "
            + "fault_id='" + fault_id + "'";


        CreateConn objcon = new CreateConn();
        objcon.SQLConnDataTable(query);
      
        GridView1.EditIndex = -1;
        loadFaultsCondition();
        // GridView1.DataBind();
        ////Bind data to the GridView control.
        //BindData();
    }
 
    protected void AddButton_Click(object sender, EventArgs e)
    {
        string faulttitle = TextBox_faulttitle.Text;
        string faultdes = TextBox_faultdes.Text;
        String insertquery = "INSERT INTO FaultsCondition(faultName,faultDes,faultType)values('" + faulttitle + "','"
            + faultdes + "',1)";
        CreateConn objconn = new CreateConn();
        DataTable dt = objconn.SQLConnDataTable(insertquery);
        loadFaultsCondition();
        GridView1.DataBind();
    }
    protected int getFaultsComponent(int faultid)
    {
        string[] str;
        str = null;
        int componentfaultsID=0;
        string query = "select c.category_id,c.category_Name from Category c join Category_Fault cf on c.category_id="
            + "cf.category_id and fault_id='" + faultid + "'";
        CreateConn objconn = new CreateConn();
        try
        {
            DataTable dt = objconn.SQLConnDataTable(query);
            if (dt != null && dt.Rows.Count > 0)
            {
                int count = 0;
                str = new string[dt.Rows.Count];
                foreach (DataRow dr in dt.Rows)
                {

                    string categoryname = dr["category_Name"].ToString();
                    str[count] = categoryname.Trim();
                    count++;
                }
                 componentfaultsID = this.CategoryNameToInt(str);
              //  Label component_lable = (Label)GridView1.FindControl("label_component");
               // component_lable.Text = this.IntToString(componentfaultsID);
            }
        }
           
        catch (Exception e)
        {
            Response.Write(e.ToString());
        }
        return componentfaultsID;
    }
    protected int CategoryNameToInt(string[] str)
    {
        switch (str.Length)
        {
            case 1:
                if (str[0] == "Pump")
                {
                    return 4;
                }
                else if (str[0] == "Gearbox")
                {
                    return 7;
                }
                else if (str[0] == "Blower")
                {
                    return 8;
                }
                else if (str[0] == "Compressor")
                {
                    return 9;
                }
                else if (str[0] == "Shaft")
                {
                    return 6;
                }
                else if (str[0] == "Motor")
                {
                    return 5;
                }
                else
                {
                    return 0;
                }
             
            case 3: string combinedstr = str[0] + str[1] + str[2];
                if(combinedstr.IndexOf("Motor")!=-1&&combinedstr.IndexOf("Gearbox")!=-1&&combinedstr.IndexOf("Pump")!=-1){
                    return 3;
                }
                return 0;
            case 5: string combinedstr2 = str[0] + str[1] + str[2]+str[3]+str[4];
                if (combinedstr2.IndexOf("Motor") != -1 && combinedstr2.IndexOf("Compressor") != -1 && combinedstr2.IndexOf("Pump") != -1 && combinedstr2.IndexOf("Shaft") != -1 && combinedstr2.IndexOf("Compressor") != -1)
                {
                    return 2;
                }
                break;
            default: return 1;
               
                    
                    
        }
        return 0;
    }
    protected string IntToString(int id)
    {
        string r = "";
        switch(id){
            case 0: r = "Not Specified"; break;
            case 1: r = "All Components"; break;
            case 2: r = "Motor, Pump, Gearbox, Compressor & Shaft"; break;
            case 3: r = "Motor, Pump&Gearbox"; break;
            case 4: r = "Pump"; break;
            case 5: r = "Motor"; break;
            case 6: r = "Shaft"; break;
            case 7: r = "Gearbox"; break;
            case 8: r = "Blower"; break;
            case 9: r = "Compressor"; break;
       


        }
        return r;
    }
    protected void UpdateFaultsComponentRealtionship(int faultid,int faultsCompnentID)
    {
        int[] catagoryIDs=null;
        switch(faultsCompnentID){

            case 1: catagoryIDs = new int[13] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 }; break;


            case 2: catagoryIDs = new int[5] { 2, 3, 4, 5,10}; break;

            case 3: catagoryIDs = new int[3] {2,3,5}; break;

            case 4: catagoryIDs = new int[1] {5 }; break;

            case 5: catagoryIDs = new int[1] {3 }; break;

            case 6: catagoryIDs = new int[1] {4}; break;

            case 7: catagoryIDs = new int[1] { 2}; break;

            case 8: catagoryIDs = new int[1] { 11}; break;

            case 9: catagoryIDs = new int[1] { 10 }; break;


        }
        string query = "Delete FROM Category_Fault where fault_id='" + faultid + "'";
        CreateConn objcon = new CreateConn();
        try{
            objcon.SQLConnDataTable(query);
        }catch(Exception e){
        }
        foreach (int i in catagoryIDs)
        {
            string query2 = "INSERT INTO Category_Fault values('" + i + "','"+faultid+"')";
            CreateConn objcon2 = new CreateConn();
            try
            {
                objcon2.SQLConnDataTable(query2);
            }catch(Exception e){
               
            }
        }
    }
    protected void LoginStatus1_LoggingOut(object sender, LoginCancelEventArgs e)
    {


        Session.Contents.Remove("UserDetails");
        Session.Abandon();
        Session.Contents.RemoveAll();
        FormsAuthentication.SignOut();
        Response.Redirect("../Default.aspx");
    }
}
